import React, { useState, useCallback, useEffect } from 'react';
import { Common } from 'UtilsCommon';
import { useGetDataSourceOptions } from 'UseHooks';
import { Tabs } from 'antd-mobile';
import Base from './base';
import PropertyItem from './propertyItem';

const getOptions = (property, view, pageAxis, parentValue) => {
    parentValue = parentValue || property.parentValue;

    Base.setValueTextName(property);
    const { valueName, textName } = property;

    const options = [];

    const { dataSource } = property;

    let value = null; let text = null;
    Common.isArray(dataSource) && dataSource.forEach(d => {
        text = d[textName];
        value = d[valueName];

        options.push({ value, text, data: d });
    });

    return options;
};

const valueChange = (property, view, pageAxis, value) => {
    if (property.valueChange) property.valueChange(value, Base.getSelectData(property, value));

    if (property.valueChangeEventActionName && property.isChanged) {
        if (!Common.isEquals(property.value2, value)) {
            pageAxis.invokeEventAction(property.valueChangeEventActionName, { property, view, pageAxis });
        }
    }
    property.value2 = value;
};

export default (props) => {
    const { property, view, pageId, pageAxis } = Base.getProps(props);

    const [value, setValue] = useState(Base.getInitValue(property));
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);
    const [options, setOptions] = useGetDataSourceOptions(property, view, pageAxis, getOptions, property.id);

    const onChange = useCallback((v) => {
        property.isChanged = true;
        setValue(v);
    }, [property, setValue]);

    useEffect(() => {
        valueChange(property, view, pageAxis, value);
    }, [property, view, pageAxis, value]);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setValue = (v) => setValue(v);
    property.getValue = () => value;
    property.refreshOptions = () => setOptions(getOptions(property, view, pageAxis));

    if (!isVisible) return null;

    const { className, style, properties } = property;

    return (
        <Tabs style={style} className={className} activeKey={value} onChange={onChange}>
            {options.map(m => <Tabs.Tab title={m.text} key={m.value} />)}
            {properties && properties.map((m, i) => <Tabs.Tab title={m.tabLabel} key={i}><PropertyItem property={m} view={property} pageId={pageId} /></Tabs.Tab>)}
        </Tabs>
    );
};